/*
 * @Description:
 * @Author: lixx
 * @Date: 2025-09-24 17:11:52
 * @LastEditTime: 2025-10-09 15:55:15
 * @LastEditors: lixx
 */
import { ref ,watch} from "vue";
import { defineStore } from "pinia";

function initState() {
  return {
    isCollapse: false,
    tagslist:[
      {
        name:'home',
        path:'home',
        label:'首页',
        path:'/home'
      }
    ],
    menuList:[],
    token:'',
    routerList:[]
  };
}

export const useAllDateStore = defineStore("allData", () => {
  /****
   * pinia 中ref 相当于state ---- data
   * computed 是getter
   * function 就是action --- methods
   */
  const state = ref(initState());
  

  // 实现路由持久化存储,使用watch监听state的变化
  watch(() => state.value, (newVal) => {
    if(!newVal.token) return
    localStorage.setItem('store', JSON.stringify(newVal))
  },{
    deep:true,
    immediate: false  // 不需要立即执行，只在变化时保存
  })

  function selectMenu(val){
    // 判断是否是首页 ,不做任何处理
    if(val.name == 'home') return 

    // 判断tagList中是否存在
    const tagIndex = state.value.tagslist.findIndex(item => item.name === val.name)
    if(tagIndex == -1){
      state.value.tagslist.push(val)
    }
  }

  // 关闭tag
  function closeTag(tag){
    const tagIndex = state.value.tagslist.findIndex(item => item.name === tag.name)
    state.value.tagslist.splice(tagIndex,1)
  }

  // 更新菜单列表
  function updateMenuList(list){
    state.value.menuList = list
  }

  // 更新token
  function updateToken(token){
    state.value.token = token
  }

  // 注册动态路由
  function addDynamicRouter(router,type){
    if(type === 'refresh'){
      if(localStorage.getItem('store')){
        state.value = JSON.parse(localStorage.getItem('store'))
        state.value.routerList = []
      }else{
        return
      }
    }
    const menu = state.value.menuList
    const module = import.meta.glob('../views/**/*.vue')
    const routerArr = []
    menu.forEach(item => {
      if(item.children){
        item.children.forEach(val => {
          let url = `../views/${val.url}.vue`
          val.component = module[url]
          routerArr.push(...item.children)
        })
      }else{
         let url = `../views/${item.url}.vue`
         item.component = module[url]
         routerArr.push(item)
      }
    })
    
    const routers = router.getRoutes()
    routers.forEach(item => {
      if(item.name == 'main' || item.name == 'login' || item.name == '404'){
        return 
      }else{
        router.removeRoute(item.name)
      }
    })
    routerArr.forEach(i => {
      state.value.routerList.push(router.addRoute('main',i))
    })
  }

  // 退出时清除信息
  function clean(){
    state.value.routerList.forEach(item => {
       if(item) item()
    })
    state.value = initState(); 
    localStorage.removeItem('store')
  }
  return {
    state,
    selectMenu,
    closeTag,
    updateMenuList,
    updateToken,
    addDynamicRouter,
    clean
  };
});
